﻿using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Threading;
using Microsoft.SmallBasic.Library;

namespace SmallBasicFun
{
	/// <summary>
	/// 	This creates a pop up box that you can use to ask for information or tell people stuff.
	/// </summary>
	[SmallBasicType]
	public static class MessageBox
	{
		private static string lastMessage;

		/// <summary>
		/// 	Prompts the user to enter some text
		/// </summary>
		/// <example>
		/// 	name = MessageBox.AskForInput("what is your name?")
		/// </example>
		/// <param name = "message">the question you want the user to answer</param>
		/// <returns>their answer</returns>
		public static Primitive AskForInput(Primitive message)
		{
			return AskForInput(message, null);
		}

		public static Primitive AskForInput(Primitive message, Action<MessageInput> secondAction)
		{
			var box = new MessageInput(message);


			Launch(new Action(() =>
			                  	{
			                  		box.BringToFront();
			                  		if (secondAction == null)
			                  		{
			                  			box.ShowDialog();
			                  			box.Close();
			                  		}
			                  		else
			                  		{
			                  			secondAction(box);
			                  		}
			                  	}));

			WaitUntil(() => box.InputResponse != null);

			return box.InputResponse;
		}


		private static void Launch(Action action)
		{
			var window = WindowManager.AllWindows.LastOrDefault();
			if (window != null)
			{
				window.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
			}
			else
			{
				action();
			}
		}

		private static void WaitUntil(Func<bool> func)
		{
			while (!func())
			{
				Thread.Sleep(30);
			}
		}

		/// <summary>
		/// 	Display a message to your end user
		/// 	<example>
		/// 		MessageBox.ShowMessage("girl programmers rule!")
		/// 	</example>
		/// </summary>
		/// <param name = "message">the message you want to display</param>
		public static void ShowMessage(Primitive message)
		{
			lastMessage = message;
			System.Windows.MessageBox.Show(message);
		}

		public static string GetLastDisplayed()
		{
			return lastMessage;
		}

		public static void MockShowMessage(string message)
		{
			lastMessage = message;
		}
	}
}